package com.tus.handler;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.util.CharsetUtil;

import static io.netty.handler.codec.http.HttpHeaderNames.*;
import static io.netty.handler.codec.http.HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

public interface Handler {

    /**
     * 获取路径前缀
     *
     * @return
     */
    String getPathPrefix();

    /**
     * 执行逻辑
     *
     * @param ctx
     * @param request
     */
    void execute(ChannelHandlerContext ctx, FullHttpRequest request);


    /**
     * 处理异常
     *
     * @param ctx
     * @param status
     * @param msg
     */
    static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status, String msg) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8));
        response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    /**
     * 添加跨域信息
     *
     * @param resp
     */
    static void addCors(FullHttpResponse resp) {
        resp.headers().set(ACCESS_CONTROL_ALLOW_HEADERS, "Origin, X-Requested-With, Content-Type, Upload-Length, Upload-Offset, Tus-Resumable, Upload-Metadata, Upload-Concat,Accept-Ranges,Expires");
        resp.headers().set(ACCESS_CONTROL_ALLOW_METHODS, "POST, HEAD, PATCH, OPTIONS");
        resp.headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
    }
}
